import cgi
import os
import datetime
import wsgiref.handlers
import gdata.service

from src.Authenticator import Authenticator

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template  


class UserIndex():
    def renderTemplate(self, response):
        
        user = users.get_current_user()
        auth = Authenticator(user)
        
        try:
            auth.client.SetAuthSubToken(auth.Profile.token)
            results = auth.client.Get("http://docs.google.com/feeds/documents/private/full")
        except gdata.service.RequestError, request_error:
            results = request_error[0]["body"]
        
        template_values = {
            'user': users.get_current_user(),
            'profile': auth.Profile,
            'auth_url': auth.Link,
            'logout_url': users.create_logout_url("/"),
            'results': results
            }
        
        path = os.path.join(os.path.dirname(__file__), '../../templates/index.html')
        response.out.write(template.render(path, template_values))


class GuestIndex():
    def renderTemplate(self, response):
        template_values = {
            'login_url': users.create_login_url("/"),
            }
        
        path = os.path.join(os.path.dirname(__file__), '../../templates/welcome.html')
        response.out.write(template.render(path, template_values))



class Welcome(webapp.RequestHandler):
    def get(self):
        
        user = users.get_current_user()
        if user:
            page = UserIndex()
        else:
            page = GuestIndex()
            
        page.renderTemplate(self.response)
        
        